import { login, logout, getInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'

const user = {
  state: {
    token: getToken(),
    name: '',
    userInfo: '',
    roles: [],
    content:''
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_USERINFO: (state, avatar) => {
      state.userInfo = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_CONT:(state, cont)=>{
      state.content = cont
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username;
      return new Promise((resolve, reject) => {

        login(username, userInfo.password).then(val => {
          //console.log(val.result);
          if(val.result == '1'){
            setToken(username);
            commit('SET_TOKEN', username);
          }else{
            commit('SET_TOKEN', '');
          }
          resolve(val)
        }).catch(error => {
          reject(error)
        })

      })
    },
    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '');
          removeToken();
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo(state.token).then(response => {
          const data = response.result;
          commit('SET_USERINFO', data);
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    },
  }
}


export default user
